﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Kaleta.Xna.Animators
{

    /// <summary>
    /// This class represents a behavorial status of a spritesheet for animating purposes.
    /// Use this class to iterate through frames in the spritesheet texture. This is it: increase the FrameIterator property
    /// and get the CurrentFrame which is the next frame in the spritesheet animation. After getting the last frame, the iterator continues from beginning. 
    /// </summary>
    public class SpriteAnimator
    {
        /// <summary>
        /// Count of all frames in the whole spritesheet texture.
        /// </summary>
        public int FrameCount { get; set; }

        /// <summary>
        /// Width of a single frame (texture).
        /// </summary>
        public int FrameWidth { get; set; }

        /// <summary>
        /// Height of a single frame (texture).
        /// </summary>
        public int FrameHeight { get; set; }

        public Texture2D Texture {get;set;}

        private float frameIterator;
        /// <summary>
        /// To iterate through all frames in the spritesheet, increase this property by 1.
        /// </summary>
        public float FrameIterator { get { return this.frameIterator; } set { frameIterator = value % FrameCount; } }

        private int sqrtFrameCount { get; set; }

        public SpriteAnimator(Texture2D texture, int frameCount, int frameWidth, int frameHeight)
        {
            Texture = texture;
            FrameCount = frameCount;
            FrameHeight = frameHeight;
            FrameWidth = frameHeight;
            frameIterator = 0;
            sqrtFrameCount = (int)Math.Sqrt(frameCount);

            if (sqrtFrameCount * sqrtFrameCount != frameCount)
                throw new ArgumentException("Invalid frame count");
        }

        /// <summary>
        /// Returns the rectangle representing current frame in sprite sheet.
        /// </summary>
        public Rectangle CurrentFrame
        {
            get
            {
                int x = (int)FrameIterator % sqrtFrameCount;
                int y = (int)FrameIterator / sqrtFrameCount;

                return new Rectangle() { X = x * this.FrameWidth, Y = y * this.FrameHeight, Width = this.FrameWidth, Height = this.FrameHeight };
            }
        }
    }
}
